<template>
    <div class="pkg-order">
        <!-- 地址信息 -->
        <div v-if="detail && detail.need_delivery && !addressId" @click="onClickAddress">
            选择地址
        </div>
        <AddressItem v-else-if="detail && detail.need_delivery && addressId"
            :name="address.name"
            :mobile="address.mobile"
            :address="address.province + address.city + address.district + address.detail"
            :tag="address.title"
            :is-default="address.is_default"
            action="编辑"
            @click="onClickAddress(address)" />

        <div class="main">
            <div class="section user-info text-normal">
                <ZbInput v-model.trim="form.name" type="text" title="姓名：" after-line="true" :input-class="['right']" placeholder="请输入联系人"></ZbInput>
                <ZbInput v-model.trim="form.phone" type="number" title="联系方式：" after-line="true" :input-class="['right']" placeholder="请输入联系方式"></ZbInput>
                <ReferrerSelect v-model="referrerKey" :can-change="canChangeReferrer" :shop-id="[shopId]" @referrerChange="handleReferrerChange"></ReferrerSelect>
                <div class="date-select people-select">
                    <div class="title">
                        <div>预定拍摄日期</div>
                    </div>
                    <div class="picker-box text-small date-picker">
                        <picker class="picker" mode="date" @change="onDateChange" :start="nowDate">
                            <div>
                                {{selectDate}}
                            </div>
                        </picker>
                        <div class="icon grey-text-color">&#xe669;</div>
                    </div>
                </div>
            </div>

            <!-- 商品信息 -->
            <div v-if="detail" class="separation"></div>
            <ProductInfoBar v-if="detail"
                :cover="detail.order_cover"
                :name="detail.name"
                :price="oldPrice" />

            <div v-if="detail" class="separation"></div>
            <div v-if="detail" class="section pay-type">
                <div class="type text-huge" @click="onClickPayType('all')" :class="{'active': payType === 'all'}">全款支付</div>
                <div class="type" v-if="detail.prepay" @click="onClickPayType('book')" :class="{'active': payType === 'book'}">
                    <span class="text-huge">定金支付</span>
                    <span class="text-small">需先支付{{prepayText}}元</span>
                </div>
            </div>
            <!-- 代金券 -->
            <div v-if="matchedDiscount" class="separation"></div>
            <!-- <ListInfoItem label="代金券选择"
                :text="selectedCoupon ? -discountValue : usableList.length + '张可用'"
                @click="toUserDiscount" /> -->
            <ListInfoItem v-if="matchedDiscount"
                label="优惠抵扣/折扣"
                :text="'-￥' + currency(matchedDiscount.total_abatement)"
                :showArrow="false" />

            <!-- 余额支付现实的金额 discountNew?discountNew.balance.is_balance:0 -->
            <!-- <div v-if="(discountNew?(discountNew.balance?(discountNew.balance.is_balance?discountNew.balance.is_balance:0):0):0) == 1 && this.payType === 'all'" class="separation"></div>
            <div v-if="(discountNew?(discountNew.balance?(discountNew.balance.is_balance?discountNew.balance.is_balance:0):0):0) == 1 && this.payType === 'all'">
                <div class="list-info-item clearfix coupon-select text-normal clearfix red-text-color" style="height:50rpx;line-height:60rpx;">
                    <div class="fl">使用充值支付</div>
                    <div class="fr red-text-color">
                        <span>
                            <input type="number" style="text-align:right" v-model="showpaymentMoney">
                        </span>
                        <span v-if="showArrow" class="icon">&#xe770;</span>
                    </div>
                </div>
                <div class="balanceTips">请注意：选择充值余额支付时，将不会产生推荐分红或返利金额！</div>
            </div> -->
            <!--  -->
            <div class="separation"></div>
            <div style="background-color: #ffffff;">
                <div class="list-info-item clearfix coupon-select text-normal clearfix" :style="checked == true ? 'padding-bottom:6rpx': ''">
                    <div class="fl" style="font-weight: bold;">使用充值支付</div>
                    <div class="fr ">
                        <span>
                            <!-- <van-switch v-model="checked" :value="checked" :disabled="disabledState"  @click="checkAwitch" active-color="#F32414" size="32rpx" @change="checkUseBalance" /> -->
                            <van-switch :value="checked" @input="onInput" :disabled="disabledState"  active-color="#F32414" size="32rpx" @click="checkAwitch" />
                        </span>
                    </div>
                </div>
                <div class="pkgbanlanceBox_down" v-if="checked">
                    <div class="balanceTips">请注意：选择充值余额支付时，将不会产生推荐分红或返利金额！</div>
                    <div class="list-info-item clearfix coupon-select text-normal clearfix" style="padding:20rpx 30rpx;">
                        <div class="fl" style="font-weight: bold;">充值支付 <span style="font-size: 22rpx;">(余额：{{thisMallRechargeMoney}})</span> </div>
                        <div class="fr">
                            <span style="display:flex;">
                                <span style="line-height:45rpx;">-￥</span>
                                <input type="number textRight" :style="{width:inputWidth(showpaymentMoney)}" v-model="showpaymentMoney">
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <!--  -->

            <div class="separation"></div>
            <div class="section price-detail">
                <div class="title after-line text-normal font-bold">价格明细</div>
                <div class="title text-small clearfix">
                    <div class="fl">原套餐价格</div>
                    <div class="fr">¥{{oldPrice | currency}}</div>
                </div>
                <div class="title text-small" v-if="sureGoodsSpec.length">
                    定制产品
                </div>
                <div class="inner text-small">
                    <div v-for="(item, index) in sureGoodsSpecCurrency" :key="index">
                        <div class="item clearfix" v-for="(val, valIndex) in item" :key="valIndex">
                            <div class="label fl grey-text-color">{{val.value}}</div>
                            <div class="val fr">¥{{val.price}} * {{val.number}}</div>
                        </div>
                    </div>
                </div>
                <!-- 优惠赠送产品 -->
                <template v-if="discount.gift && discount.gift.length">
                    <div class="title text-small color-primary">
                        优惠赠送产品
                    </div>
                    <div class="inner text-small">
                        <template v-for="(gift, x) in discount.gift">
                            <div class="item clearfix" :key="x + '_y'">
                                <div class="label fl grey-text-color">{{gift.title}}</div>
                            </div>
                            <div class="item item--indent clearfix" v-for="(item, y) in gift.content" :key="x + '_' + y">
                                <div class="label fl grey-text-color">{{item.attr_value}}</div>
                                <div class="val fr">¥0 * {{item.number}}</div>
                            </div>
                        </template>
                    </div>
                </template>
                <!-- 优惠抵扣/折扣 -->
                <!-- <div v-if="matchedDiscount" class="title text-small clearfix color-primary">
                    <div class="fl">优惠抵扣/折扣</div>
                    <div class="fr">-¥{{matchedDiscount.total_abatement | currency}}</div>
                </div> -->
                

                <div class="title before-line clearfix text-normal">
                    <div class="fl">全款金额</div>
                    <div class="fr">
                        <span class="text-small">小计&emsp;</span>
                        <span>¥{{totalPrice | currency}}</span>
                    </div>
                </div>
            </div>

            <div class="separation"></div>
            <div class="pkg-order__remark">
                <div class="pkg-order__remark-title after-line narrow">添加备注</div>
                <textarea v-model.trim="form.remark"
                    class="pkg-order__remark-text"
                    placeholder="点击输入">
                </textarea>
                <div class="pkg-order__remark-hint">
                    {{form.remark.length}}/100
                </div>
            </div>
        </div>
<!-- discountNew?(discountNew.balance?(discountNew.balance.is_balance?discountNew.balance.is_balance:0):0):0 -->
        <OrderPriceBar :price="payPrice" :isBalance="0" :is-paying="isPaying" @pay="onClickPay" />

        <!-- <OrderPriceBar :price="payPrice" :isBalance="discountNew?(discountNew.balance?(discountNew.balance.is_balance?discountNew.balance.is_balance:0):0):0" :is-paying="isPaying" @pay="onClickPay" /> -->
        <!-- <OrderPriceBar :price="payPrice" :isBalance="discount.discount?discount.discount.balance.is_balance:0" :is-paying="isPaying" @pay="onClickPay" /> -->

        <!-- 取消支付后弹窗 -->
        <van-dialog v-model="showCancelPopup"
            title="确认要离开收银台"
            message="你的订单在2小时内未支付将被取消，要重新支付本订单，请在“我的”菜单页面，“待付款”中找到该订单进行支付"
            show-cancel-button
            cancel-button-text="确认离开"
            confirm-button-text="继续支付"
            @confirm="onConfirmPay(orderId,payType)"
            @cancel="onCancelPay(orderId,payType)">
        </van-dialog>
    </div>
</template>

<script lang="ts">
import { api } from '@/lib/api';
import { dateFormat, dateNow, dateParse, currency, wait } from '@/lib/utils';
import { EMPTY_LIST } from '@/lib/constant';
import { ROUTE_NAME, STATUS_LOGIN_LOGINED } from '@/lib/constant';
import store from '@/store';
import AddressItem from '@/features/order/addressItem.vue';
import ZbInput from '@/components/common/zbInput.vue';
import ProductInfoBar from '@/features/product/infoBar.vue';
import OrderPriceBar from '@/features/order/priceBar.vue';
import ListInfoItem from '@/components/list/infoItem.vue';
import ReferrerSelect from '@/features/order/referrerSelect.vue';
import { Component, Mixins, Vue, Watch } from 'vue-property-decorator';
import { checkMobile, checkValidate, ValidateRule } from '@/lib/script/validate';
import { ShowRdata } from '@/mixins/showRdata';
import { watch } from 'fs';

@Component({
    name: 'PkgOrder',
    components: {
        AddressItem,
        ZbInput,
        ProductInfoBar,
        OrderPriceBar,
        ListInfoItem,
        ReferrerSelect,
    },
    methods: {
        currency,
    },
})
export default class PkgOrder extends Mixins(ShowRdata) {
    public isBalance = null;
    public isPaying = false;
    public peopleIndex: any = 0;
    public form = {
        name: '',
        phone: '',
        remark: '',
    };
    public referrerKey: any = '';
    public dateNow: any = dateNow();
    public nowDate: any = dateFormat(dateNow());
    public selectDate: any = dateFormat(dateNow());
    public payType: any = 'all';
    public updateCoupon: any = true;
    public peopleSelectOptionsVisible: any = false;
    public selectedReferrer: any = null;
    /** 上次支付的订单id */
    public orderId: number | null = null;
    /** 取消支付后弹窗 */
    public showCancelPopup = false;

    public canChangeReferrer: any = true;
    // debounceGetReferrerList: null,

     // 显示余额支付 1
     public discountNew: any = {
        full_reduction: [],
        discount: [],
        balance: {
            is_balance: 0,
            is_recharge: 0,
            recharge_money: 0
        }
     };

    // 计算input宽度
    public get inputWidth(){
        return function (value) {
            if (value == '' || value == 0) {
            return '130rpx'
            } else {
            return String(value).length * 0.55 + 'rem'
            }
        }
    }
    // 滑块选中状态
    public checked:any = false;
    // 滑块是否禁用
    // public disabledState:any = false;
    // 滑块点击方法
    public onInput(checked){
        if(this.shopBalance > 0){
            this.checked = checked;
        }else{
            this.checked == false;
            wx.showToast({
                title: '余额支付不足',
                icon: 'none',
            });
        }
    }
    public checkAwitch(){
        if(this.disabledState == true){  // 商品不支持余额支付 is_balance == 0
            if(this.payType == 'all'){
                wx.showToast({
                    title: '该商品非充值余额支付商品',
                    icon: 'none',
                });
            }else{
                wx.showToast({
                    title: '不支持充值支付',
                    icon: 'none',
                });
            }
            
        }
    }
    //  监听开关状态
     @Watch('checked')
     public changeChecked(){
        if(this.checked == false){
            this.showpaymentMoney = 0;
        }else{
            this.showpaymentMoney = this.thisMallRechargeMoney;
        }
        
     }
     public get disabledState(){
         return (this.discountNew?(this.discountNew.balance?(this.discountNew.balance.is_balance?this.discountNew.balance.is_balance:0):0):0) == 1 && this.payType === 'all' ? false : true;
     }

    // 新增订单混合支付
    // 当前用户在门店中余额
    public thisMallRechargeMoney: any = 0;
    // 页面显示金额
    public showpaymentMoney: any = 0;

    @Watch('showpaymentMoney')
    public OnthisMallRechargeMoney() {
        if(this.checked == false){
            this.showpaymentMoney = 0;
        }else{
            // 商品金额 小于 当前门店金额 = 显示当前商品金额
            if (this.totalPrice <= this.showpaymentMoney * 100) {
                // 返回商品金额减去门店金额 = 所需支付的金额
                this.showpaymentMoney = Math.trunc( this.totalPrice/100);
                return;
            }
            // 支付方式 全款支付 只操作全款支付
            // this.payType === 'book' ? this.prepayPrice : this.totalPrice
            let newMoney = this.showpaymentMoney; // 支付金额
                if(this.payType === 'all' && (this.discountNew?this.discountNew.balance.is_balance:0)){
                    // 修改金额 小于 需支付金额
                    if(newMoney*100 > this.thisMallRechargeMoney * 100){
                        wx.showToast({
                            title: '账户余额不足',
                            icon: 'none',
                        });
                        this.showpaymentMoney = this.thisMallRechargeMoney;
                        return;
                    }
                    if(newMoney*100 > this.totalPrice){
                        wx.showToast({
                            title: '修改的金额不能大于支付金额',
                            icon: 'none',
                        });
                        this.showpaymentMoney = Math.trunc(this.totalPrice/100);
                        return;
                    }
                    // 修改金额 大于 0
                    if(newMoney*100 < 0){
                        wx.showToast({
                            title: '金额不能大于订单金额',
                            icon: 'none',
                        });
                        this.showpaymentMoney = 0;
                        return;
                    }
                }
        }
    }

    // 获取会员在个店铺中的余额
    public get getshopBalance(){
        return store.state.user.shopBnlance;
    }
    public get shopBalance(){
        let balance = 0;
        for(var i=0;i< this.getshopBalance.length;i++){
            if(this.getshopBalance[i].shop_id == this.shopId){
                balance = this.getshopBalance[i].balance;
            }
        }
        return balance;
    }
// 





    public get shopId() {
        return this.$route.params.shopId;
    }
    public get pkgId() {
        return this.$route.params.pkgId;
    }
    public get type() {
        return this.$route.params.type;
    }
    public get referrerId() {
        return this.$route.query.referrer;
    }
    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }
    public get hasLogin() {
        return store.state.auth.hasLogin;
    }
    /** 套系商品 */
    public get productDetailMap() {
        return store.state.pkg.productDetailMap;
    }
    public get productSpecMap() {
        return store.state.pkg.productSpecMap;
    }
    public get sureGoodsSpecMap() {
        return store.state.pkg.sureGoodsSpecMap;
    }
    public get selectedGoodsSpecMap() {
        return store.state.pkg.selectedGoodsSpecMap;
    }
    public get referrer() {
        return store.state.user.referrer;
    }
    public get bindReferrerId() {
        return store.state.user.bindReferrerId;
    }
    public get referrerList() {
        return store.state.user.referrerList;
    }

    /** 代金券列表 */
    public get couponList() {
        return store.state.user.couponList;
    }

    /** 代金券数据 */
    public get couponMap() {
        return store.state.user.couponMap;
    }

    /** 所属店铺 */
    public get memberShopList() {
        return store.state.user.memberShopList;
    }

    /** 代金券id */
    public get couponId() {
        return store.state.order.couponId;
    }

    /** 地址id */
    public get addressId() {
        return store.state.order.addressId;
    }

    /** 所属店铺id */
    public get memberShopIdList() {
        return this.memberShopList.map((item: any) => {
            return String(item.shop_id);
        });
    }
    public get isDisabled() {
        return this.referrer !== null;
    }
    /** 列表 */
    public get wrap() {
        return this.couponList['useable'] || EMPTY_LIST;
    }
    /** 列表 */
    public get list() {
        return this.wrap.list.map((id: any) => this.couponMap[id]);
    }
    /** 可以使用的代金券 */
    public get usableList() {
        return this.list.filter((coupon: any) => {
            return this.checkCoupon(coupon);
        });
    }
    /** 最大最快到期的代金券 */
    public get maxUsableCoupon() {
        let resultCoupon = null;
        let resultDiscountValue = null;
        this.usableList.forEach((item: any) => {
            if (!resultCoupon) {
                resultCoupon = item;
                resultDiscountValue = this.getDiscountValue(item);
            } else {
                const tempDiscountValue = this.getDiscountValue(item);
                if (tempDiscountValue > resultDiscountValue) {
                    resultCoupon = item;
                    resultDiscountValue = tempDiscountValue;
                } else if (tempDiscountValue === resultDiscountValue) {
                    if (dateParse(resultCoupon.expiration_date).valueOf() > dateParse(item.expiration_date).valueOf()) {
                        resultCoupon = item;
                        resultDiscountValue = tempDiscountValue;
                    }
                }
            }
        });
        return resultCoupon;
    }
    public get selectedCoupon() {
        return this.couponId ? this.couponMap[this.couponId] : null;
    }
    /** 折扣金额 */
    public get discountValue() {
        if (!this.selectedCoupon) {
            return 0;
        }
        return currency(this.getDiscountValue(this.selectedCoupon));
    }
    public get detail() {
        return this.pkgId && this.productDetailMap[this.pkgId] ? this.productDetailMap[this.pkgId] : null;
    }
    public get productSpec() {
        return this.pkgId && this.productSpecMap[this.pkgId] ? this.productSpecMap[this.pkgId] : [];
    }
    /** todo: 这是什么 */
    public get sureGoodsSpec() {
        return this.pkgId && this.sureGoodsSpecMap[this.pkgId] ? this.sureGoodsSpecMap[this.pkgId] : [];
    }
    public get sureGoodsSpecCurrency() {
        return this.sureGoodsSpec.map((item: any) => {
            return item.filter((itemA: any) => {
                return itemA.number > 0;
            }).map((val: any) => {
                return Object.assign(JSON.parse(JSON.stringify(val)), {
                    price: val.price,
                });
            });
        });
    }
    public get selectedSpecIds() {
        return this.sureGoodsSpec.length ? this.sureGoodsSpec.map((item: any) => {
            return item.filter((val: any) => {
                return val.number > 0;
            });
        }).flat(Infinity).map((temp: any) => {
            return {
                id: temp.id,
                number: temp.number,
            };
        }) : [];
    }
    /** 优惠信息 */
    public get discount() {
        return store.state.pkg.discount[Number(this.pkgId)] || {
            discount: [],
            full_reduction: [],
            gift: [],
            balance: {
                is_balance: 0,
                is_recharge: 0,
                recharge_money: 0
            }
        };
    }
    /** 所使用的优惠 */
    public get matchedDiscount() {
        const price = this.realPrice;
        let result: (Pkg.FullReductionDiscount & { total_abatement: number; }) | null = null;
        // 存储当前门店余额
        this.thisMallRechargeMoney = this.shopBalance;
        // this.showpaymentMoney = this.shopBalance;
        this.discountNew = this.discount;
        

        for (let item of this.discount.full_reduction || []) {
            if (price >= item.limit) {
                if (!result) {
                    result = {
                        ...item,
                        total_abatement: item.abatement * Math.floor(price / item.limit),
                    };
                } else {
                    const totalAbatement = item.abatement * Math.floor(price / item.limit);
                    if (totalAbatement > result.total_abatement) {
                        result = {
                            ...item,
                            total_abatement: totalAbatement,
                        };
                    }
                }
            }
        }
// 新增折扣测试
        for (let item of (this.discount.discount || [])) {
            if (price >= item.limit) {
                if (!result) {
                    result = {
                        id: item.id,
                        title: item.title,
                        limit: item.limit,
                        abatement: item.ratio,
                        total_abatement: (price / item.limit) * (100 - item.ratio),
                    };
                } else {
                    
                    const totalAbatement = (price / item.limit) * (100 - item.ratio);
                    if (totalAbatement > result.total_abatement) {
                        result = {
                            id: item.id,
                            title: item.title,
                            limit: item.limit,
                            abatement: item.ratio,
                            total_abatement: totalAbatement,
                        };
                    }
                }
            }
        }
        if (!result) {
            return null;
        } else {
            return result;
        }
        // return result;
    }
    public get oldPrice() {
        return this.detail?.price;
    }
    public get defaultSpecPrice() {
        if (this.detail && this.productSpec.length) {
            let total = 0;
            this.productSpec.map((item: any) => {
                return item.values.filter((val: any) => {
                    return val.is_default;
                });
            }).forEach((item: any) => {
                item.forEach((val: any) => {
                    total += Number(currency(val.price * val.discount * val.number));
                });
            });
            return total * 100;
        }
        return 0;
    }
    /** 现在价格 */
    public get realPrice() {
        if (this.detail) {
            if (this.sureGoodsSpec.length) {
                let total = 0;
                // todo: 感觉应该是修改过的规格信息
                this.sureGoodsSpec.forEach((item: any) => {
                    item.forEach((val: any) => {
                        total += Number(currency(val.price * val.discount * val.number));
                    });
                });
                return Math.trunc(Number(this.detail.price) + total * 100 - this.defaultSpecPrice);
            }
            return Math.trunc(Number(this.detail.price));
        }
        return 0;
    }
    /** 总价格 */
    public get totalPrice() {
        if (this.realPrice - Number(this.discountValue) * 100 > 0) {
            return this.realPrice - Number(this.discountValue) * 100 - (this.matchedDiscount?.total_abatement || 0);
        }
        return 0;
    }
    /** 支付价格 */
    public get payPrice() {
        return this.payType === 'book' ? this.detail.prepay : (this.discountNew?(this.discountNew.balance?(this.discountNew.balance.is_balance?this.totalnewpayPrice:this.totalPrice):this.totalPrice):this.totalPrice);
        // return this.payType === 'book' ? this.detail.prepay : this.totalPrice;
    }
    /** 全款支付使用混合支付显示的支付价格 */
    public get totalnewpayPrice() {
        // 当前门店金额大于0
        if(this.showpaymentMoney > 0){
            // 如果支付金额大于当前门店金额，显示充值金额为商品金额
            if (this.totalPrice >= this.showpaymentMoney * 100) {
                // 返回商品金额减去门店金额 = 所需支付的金额
                return this.totalPrice - this.showpaymentMoney * 100;
            }else{
                this.totalPrice;
            }
        }else{
            return this.totalPrice
        }

    }

    public get prepayText() {
        return this.detail && this.detail.prepay ? currency(this.detail.prepay) : 0;
    }
    /** 检查规则 */
    public get rules(): { [key: string]: ValidateRule[] } {
        return {
            name: [
                { required: true, message: '请填写联系人' },
            ],
            phone: [
                { required: true, message: '请填写联系方式' },
                { fn: checkMobile, message: '请填写正确的手机号' },
            ],
        };
    }

    @Watch('form.remark')
    public onFormRemark() {
        const remark = this.form.remark;
        if (remark.length > 100) {
            this.form.remark = remark.slice(0, 100);
        }
    }

    public handleReferrerChange(referrer: any) {
        this.selectedReferrer = referrer;
    }
    public onDateChange(e: any) {
        this.selectDate = e.target.value;
    }
    public onClickPayType(type: any) {
        this.payType = type;
        if(this.payType == 'book'){
            this.checked = false;
        }
    }
    /**
     * 计算折扣金额
     */
    public getDiscountValue(coupon: any) {
        const number = Number(coupon.money);
        return number;
    }
    /**
     * 检查是否可用代金券
     */
    public checkCoupon(coupon: any) {
        const matchGood = !coupon.applicable ? true : coupon.applicable.indexOf(String(this.pkgId)) !== -1;
        const matchShop = !coupon.shop_id ? true : (Number(coupon.shop_id) === Number(this.shopId));
        const matchPrice = Number(coupon.price_limit) <= Number(this.realPrice);
        const matchTime = this.dateNow.valueOf() <= dateParse(coupon.expiration_date).valueOf();
        const matchType = !coupon.type ? true : (coupon.type === 'package');
        return matchGood && matchShop && matchPrice && matchTime && matchType;
    }
    /**
     * 去代金券页面
     */
    public toUserDiscount() {
        // api.navigateTo({
        //     url: '/pages/coupon_select/main',
        //     query: {
        //         is_select: 1,
        //         price: this.realPrice,
        //         type: 'package',
        //         shop_id: this.shopId,
        //         pkg_id: this.pkgId,
        //     },
        // });
        api.push({
            name: ROUTE_NAME.MALL_COUPON_SELECT,
            query: {
                isSelect: '1',
                price: this.realPrice + '',
                type: 'package',
                shop_id: this.shopId,
                pkg_id: this.pkgId,
            },
        });
    }
    /**
     * 点击地址
     */
    public onClickAddress() {
        // api.navigateTo({
        //     url: '/pages/address_list/main',
        //     query: {
        //         enable_select: 1,
        //     },
        // });

        api.push({
            name: ROUTE_NAME.ADDRESS_LIST,
            query: {
                enableSelect: '1',
            },
        });
    }
    /**
     * 点击支付
     */
    public async onClickPay(_type) {
        let ispayType = 0;
        if(_type == 'balance'){
            ispayType = 1
        }else{
            ispayType = 0
        }
        // balance  余额支付
        // cash  原支付方式（微信支付）
        if (!this.selectDate) {
            wx.showToast({
                title: '请完整填写信息',
                icon: 'none',
            });
            this.isPaying = false;
            return;
        }
        const keys = Object.keys(this.rules);
        for (const key of keys) {
            const fail = checkValidate(this.form[key], this.rules[key]);
            if (fail) {
                wx.showToast({
                    title: fail.message,
                    icon: 'none',
                });
                return;
            }
        }

        // 创建订单
        store.commit('utils/startRequest');
        this.isPaying = false;
        // 进入订单支付
        const payRes = await store.dispatch('order/createPkgOrder', {
            packageId: this.pkgId,
            referrerId: this.selectedReferrer ? this.selectedReferrer.id : null,
            spec: this.selectedSpecIds,
            couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
            deliverDate: this.selectDate,
            name: this.form.name,
            mobile: this.form.phone,
            isPrepay: this.payType === 'book',
            remark: this.form.remark,
            hasDiscount: !!this.matchedDiscount,
            // payType: ispayType,
            payType: this.payType == 'all'? (this.showpaymentMoney > 0? 1 : 0) : 0,
            balance_pay: this.payType == 'all'? this.showpaymentMoney* 100 : 0,
        });
        if (payRes.statusCode !== 200 || payRes.data.status !== 0) {
            store.commit('utils/endRequest');
            wx.showToast({
                title: payRes.data.message,
                icon: 'none',
            });
            return;
        }
        const orderId = this.orderId = payRes.data.data.id;
        const params = payRes.data.data.params;
        this.updateCoupon = true;
        // 没有参数
        if (!params) {
            store.commit('utils/endRequest');
            // api.redirectTo({
            //     url: `/pages/order_result/main?type=package&order_id=${orderId}`,
            // });
            api.push({
                name: ROUTE_NAME.ORDER_RESULT,
                params: {
                    type: 'pkg',
                    orderId: orderId + '',
                },
            });
            return;
        }
        store.commit('utils/endRequest');
        if(_type == 'balance'){
            wx.showToast({
                title: '购买成功',
                icon: 'success',
            });
            setTimeout(() => {
                api.push({
                    name: ROUTE_NAME.ORDER_RESULT,
                    params: {
                        type: 'pkg',
                        orderId: orderId + '',
                    },
                });
            }, 1000);
        }else{
            // 微信支付
            this.onConfirmPay(orderId, params);
        }
        
    }
    /**
     * 取消支付
     */
    public onCancelPay(orderId: number,payType: number) {
        store.dispatch('order/checkBackSendMsg', {
            orderId:orderId,
            type: 'taoxi',
            pickType: '',
            payType: payType,
            forceUpdate: true,
        });
        api.push({
            name: ROUTE_NAME.ORDER_LIST,
            query: {
                status: 'init',
            },
        });
    }
    /**
     * 微信 确认支付
     */
    public async onConfirmPay(orderId: number, params?: any) {
        // 余额支付  pay_type ：1 微信支付： 0

        if (!params) {
            store.commit('utils/startRequest');
            const res = await store.dispatch('order/pay', {
                orderId
            });
            store.commit('utils/endRequest');

            this.showRdata(res.data, '', () => {
                params = res.data.data;
            });
        }
        // 触发微信支付
        const result = await api.requestPayment({
            ...params,
            timeStamp: params.timestamp,
        }).catch((err: any) => {
            return err;
        });

        if (result && result.errMsg.indexOf('requestPayment:ok') >= 0) {
            // 轮询
            store.commit('utils/startRequest');
            let success = false;
            for (let i = 0; i < 20; i++) {
                const res = await store.dispatch('order/getPayStatus', {
                    id: orderId,
                });
                if (res.statusCode !== 200 || res.data.status !== 0) {
                    wx.showToast({
                        title: '发生了一些错误',
                        icon: 'none',
                    });
                    break;
                } else if (res.data.data !== 'init') {
                    success = true;
                    break;
                } else {
                    await wait(1000);
                }
            }
            store.commit('utils/endRequest');

            if (success) {
                wx.showToast({
                    title: '购买成功',
                    icon: 'success',
                });

                setTimeout(() => {
                    api.push({
                        name: ROUTE_NAME.ORDER_RESULT,
                        params: {
                            type: 'pkg',
                            orderId: orderId + '',
                        },
                    });
                }, 1000);
            }
        } else {
            if (result.errMsg.indexOf('requestPayment:fail cancel') >= 0) {
                store.dispatch('order/getList', {
                    status: 'init',
                    offset: 0,
                    count: 10,
                    forceUpdate: true,
                });
                this.showCancelPopup = true;
            }
        }
    }

    /**
     * query
     * - type: book | all
     */
    public async created() {
        // this.debounceGetReferrerList = debounce(this.getReferrerList, 500);
        this.referrerKey = '暂无推荐人邀请';
        this.selectedReferrer = null;
        this.updateCoupon = true;
        store.commit('utils/startRequest');
        this.payType = this.type === 'book' ? 'book' : 'all';
        this.isPaying = false;
        this.canChangeReferrer = true;
        // const isFromShare = query.is_from_share === 'true';
        if (this.bindReferrerId) {
            const referrerRdata = await store.dispatch('user/checkReferrer', {
                shopId: [ this.shopId ],
                userId: this.bindReferrerId,
            });
            if (referrerRdata.status === 0 && referrerRdata.data) {
                this.selectedReferrer = referrerRdata.data;
                this.referrerKey = this.selectedReferrer.name || this.selectedReferrer.nickname;
                this.canChangeReferrer = false;
            }
        } else {
            // 返利会员自己所属店铺 商家职员和城市合伙人下单返利为自己
            if (this.memberShopIdList.includes(String(this.shopId)) || this.userBasicInfo.level > 1) {
                this.selectedReferrer = this.userBasicInfo;
                this.referrerKey = this.selectedReferrer.name || this.selectedReferrer.nickname;
            }
            // else if (this.referrer) {
            //     this.selectedReferrer = this.referrer;
            //     this.referrerKey = this.referrer.name || this.referrer.nickname;
            // }
        }
        await Promise.all([
            store.dispatch('pkg/getDetail', {
                pkgId: this.pkgId,
            }),
            store.dispatch('pkg/getProductSpec', {
                pkgId: this.pkgId,
            }),
            store.dispatch('pkg/getDiscount', {
                pkgId: this.pkgId,
                referrer: this.referrerId,
            }),
            // store.dispatch('user/getReferrerInfo'),
            store.dispatch('user/getMemberShopList'),
            store.dispatch('user/getShopBanlance'),
        ]);
        store.commit('utils/endRequest');
    }
    public async mounted() {
        if (this.updateCoupon) {
            /** 假设设置的全部代金券，需要在某个地方获取所有可用代金券 */
            await store.dispatch('user/getCouponList', {
                status: 'useable',
                offset: 0,
                count: 100,
            });
            const coupon = this.maxUsableCoupon;
            store.commit('order/setCouponId', coupon ? coupon.id : null);
            this.updateCoupon = false;
        }
    }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.pkg-order {
    box-sizing: border-box;
    min-height: 100%;
    padding-bottom: 50px + 10px;
    background-color: @nav-grey-color;

    .section {
        background-color: @white-color;
    }
    .user-info {
        .people-select {
            position: relative;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 30rpx;
            .date-picker {
                box-sizing: border-box;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border: 2rpx solid #BBBBBB;
                border-radius: 10rpx;
                width: 224px;
                height: 24px;
                padding: 10rpx 16rpx;
                .picker {
                    flex: 1;
                }
            }
        }
    }
    .pay-type {
        display: flex;
        justify-content: space-around;
        padding: 15px 0rpx;
        .type {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            width: 152px;
            height: 53px;
            border-radius: 14rpx;
            border: 2rpx solid #bbb;
            background-color: #f5f5f5;
            &.active {
                color: #F13C50;
                border: 2rpx solid #F13C50;
                background-color: rgba(241, 60, 80, 0.09);
            }
        }
    }
    .price-detail {
        padding: 0 17px;
        .title {
            position: relative;
            padding: 22rpx 0;
        }
        .inner {
            padding-left: 40rpx;
            .item {
                margin: 10rpx 0;
                &--indent {
                    padding-left: 15px;
                }
            }
        }
    }

    &__remark {
        background-color: @color-white;
        &-title {
            position: relative;
            padding: 10px 15px;
            .text-normal();
            .font-semi();
        }
        &-text {
            width: 100%;
            height: 90px;
            padding: 10px 15px;
            .text-normal();
            box-sizing: border-box;
        }
        &-hint {
            padding: 0 15px 10px;
            .text-small();
            color: @color-font-3;
            text-align: right;
        }
    }
}
</style>
